import datetime
import json
import os
import sys

import boto3
from smart_open import open

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from project_utils.sqlserver_conncet import ReadFromSqlServer
from config import *

ac365_sqlserver = ReadFromSqlServer(host=sqlserver_host, user=sqlserver_user, password=sqlserver_password,
                                    port=sqlserver_port)
ac365_sqlserver.makepool(sqlserver_database)
s3 = boto3.client("s3")

sql = """
    select
        ac365Id as ac365_id,
        contactName as contact_name,
        contactPhone1 as contact_phone1,
        contactPhone2 as contact_phone2,
        detailAddress as detail_address,
        gbm as gbm,
        aztime as aztime,
        buyDate as buy_date,
        buyMarket as buy_market,
        receiptCode as receipt_code,
        productModel as product_model,
        productSn as product_sn,
        outerCode as outer_code,
        cpz as cpz,
        lrtype as lrtype,
        GlzxName as glzx_name,
        KydDqName as kyd_dq_name,
        KydFgsName as kyd_fgs_name,
        aznet as aznet,
        azdwmc as azdwmc,
        hfyp as hfyp,
        hfResult as hf_result,
        tag as tag,
        njlrtype as njlrtype,
        wjlrtype as wjlrtype,
        srvOrdId as srv_ord_id,
        external_order_no as external_order_no,
        IsYc as is_yc,
        cjrq as cjrq 
    """



# 执行导入程序
def run(start="", end=""):
    # 如果没有指定日期，则读取上一次记录的增量时间
    if not (start and end):
        pass
    else:
        start = datetime.datetime.strptime(start, '%Y-%m-%d')
        end = datetime.datetime.strptime(end, '%Y-%m-%d')
    # 将时间分割为1天为单位
    if start and end:
        times = split_time_month(start, end)
        # 每天单独导入一次
        for i in times:
            sql2 = f"{sql} FROM [dbo].[V_Hm]  where cjrq between '{i[0]}' and '{i[1]}' "
            print("执行sql:", sql2)
            rs = ac365_sqlserver.read(sql2)
            print("结果数量:", len(rs))
            write_to_s3(str(i[1][0:7]), rs)
            # print(rs)


# 写入S3
def write_to_s3(date, rs):
    # 有数据才写入
    if len(rs) > 0:
        file_name = f"{ac365_location_all}/import_date={date}/{date}-{datetime.datetime.now().timestamp()}.json.gz"
        # 使用smart-open框架写入S3
        # session = boto3.Session(region_name=FORMAL_S3_CONFIG['region_name'],
        #                         aws_access_key_id=FORMAL_S3_CONFIG["access_key"],
        #                         aws_secret_access_key=FORMAL_S3_CONFIG["secret_key"])
        transport_params = {'client': s3}

        # 写出通道
        with open(file_name, 'w', compression='.gz', encoding='utf-8', transport_params=transport_params) as fw:
            length = len(rs)
            for i in range(0, length):
                one = rs[i]
                for key in one:
                    one[key] = str(one[key])
                if i == length - 1:
                    fw.write(json.dumps(one, ensure_ascii=False))
                else:
                    fw.write(json.dumps(one, ensure_ascii=False) + "\n")
        print("写入文件" + file_name + "成功")


# 分割时间为一天一天格式
def split_time_month(start, end):
    list = []
    if start > end:
        return list
    begin = start
    month = 1 if begin.month + 1 > 12 else begin.month + 1
    year = (begin.year + 1) if month == 1 else begin.year

    stop = datetime.datetime(year=year, month=month, day=1) + datetime.timedelta(days=-1)
    while True:
        if stop > end:
            stop = end
        print([begin.strftime('%Y-%m-%d'), stop.strftime('%Y-%m-%d')])
        list.append([begin.strftime('%Y-%m-%d'), stop.strftime('%Y-%m-%d')])
        month = 1 if month + 1 > 12 else month + 1
        year = (year + 1) if month == 1 else year
        begin = stop + datetime.timedelta(days=1)
        stop = datetime.datetime(year=year, month=month, day=1) + datetime.timedelta(days=-1)
        if begin > end:
            break

    return list


if __name__ == '__main__':
    # print(split_time_month(datetime.datetime.strptime('2022-01-01', '%Y-%m-%d'),
    #                        datetime.datetime.strptime('2023-12-31', '%Y-%m-%d')))
    # try:
    event = json.loads(sys.argv[1])
    run(event['start'], event['end'])
#     tasktoken = event.get('TaskToken')
#     if "start" in event:
#         run(event['start'], event['end'])
#     else:
#         run()
# except Exception as e:
#     print_to_log("任务失败")
#     print_to_log("原因： ", str(e))
#     send_task_failure(str(e), str(e), tasktoken)
